package com.example.mobile2021606163crw0523;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class NewsRVAdapter extends RecyclerView.Adapter<NewsRVAdapter.ViewHolder> {
    private List<News> newsList;
    public NewsRVAdapter(List<News> newsList){
        this.newsList = newsList;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //通过LayoutInflater获取列表项布局文件对象（即控件），接着创建ViewHolder对象
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_rv_main_news, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //通过position获取数据，然后赋值给控件
        News news = newsList.get(position);
        holder.tvItemID.setText(String.valueOf(news.getId()));
        holder.tvItemTitle.setText(news.getTitle());
    }

    @Override
    public int getItemCount() {
        //重写getItemCount（）方法，用于获取数据的长度
        return newsList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tvItemID,tvItemTitle;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvItemID = itemView.findViewById(R.id.tvItemID);
            tvItemTitle = itemView.findViewById(R.id.tvItemTitle);
        }
    }
}
